package by.vr.jpa.result.transformer.dao.impl;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import by.vr.jpa.result.transformer.dao.api.GenericDao;
import by.vr.jpa.result.transformer.dao.api.QueryParam;
import by.vr.jpa.result.transformer.impl.TransformUtil;

public class GenericDaoImpl <T, K> implements GenericDao<T, K> {
	
	private static final Logger logger = LoggerFactory.getLogger(GenericDaoImpl.class);
	
	
	@PersistenceContext()
	private EntityManager em;

	public List<T> find(String queryName, List<QueryParam> params) {
		
		
		// TODO Auto-generated method stub
		return null;
	}

	public T findOne(String queryName, List<QueryParam> params) {
		// TODO Auto-generated method stub
		return null;
	}

	public <N> List<N> findObjects(String queryName, List<QueryParam> params) {
		
		if(logger.isDebugEnabled()){
			logger.debug("Executing query [" + queryName + "] with parameters [" + params + "]");
		}
		
		final Query query = createNamedQuery(queryName, params);
		final List<N> resultList = query.getResultList();
		if(logger.isDebugEnabled()){
			logger.debug("Fetched by query [" + queryName + "] " + resultList.size() + " records");
		}
		return resultList;
	}

	public <N> N findObject(String queryName, List<QueryParam> params) {
		// TODO Auto-generated method stub
		return null;
	}

	public List<T> findLazy(String queryName, List<QueryParam> params) {
		final List<Object[]> tuples = findObjects(queryName, params);
		final List<T> resultList = TransformUtil.transform(entityClass, tuples, hqlQuery)
		return null;
	}

	public T findLazyOne(String queryName, List<QueryParam> params) {
		// TODO Auto-generated method stub
		return null;
	}

	public <N> List<N> findLazyObjects(String queryName, List<QueryParam> params) {
		// TODO Auto-generated method stub
		return null;
	}

	public <N> N findLazyObject(String queryName, List<QueryParam> params) {
		// TODO Auto-generated method stub
		return null;
	}
	
	
	
	private Query createNamedQuery(final String queryName, List<QueryParam> params){
		final Query query = em.createNamedQuery(queryName);
		if(params != null){
			for(QueryParam param : params){
				query.setParameter(param.getName(), param.getValue());
			}
		}
		return query;
	}

}
